package com.aruba.springsecuritystudy.config;

import com.aruba.springsecuritystudy.security.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PersistentTokenRepository repository;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/showLogin")//登录页面处理单元
                .loginProcessingUrl("/login")//登录时提交的请求
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.sendRedirect("/main");
                    }
                });
//                .successForwardUrl("/main");//登录成功处理单元

        http.authorizeRequests()
                .antMatchers("/showLogin").permitAll() //配置不需要被认证的请求
                .antMatchers(HttpMethod.GET, "/js/**").permitAll()
                .antMatchers("/register").hasAuthority("register")//只有有注册权限
                .antMatchers("/modify").hasAnyAuthority("modify", "register")//任意一个权限
                .antMatchers("/manage").hasRole("admin")//只有admin角色
                .antMatchers("/show").hasAnyRole("admin", "user")//任意一个角色
                .anyRequest().access("@myAccessServiceImpl.hasPermission(request,authentication)");
//                .anyRequest().authenticated();//其他请求都必须被认证。必须登录后才能访问。

        http.csrf().disable();

        // 拒绝访问的处理
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                response.setHeader("Content-Type", "application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write("{\"status\":\"error\",\"msg\":\"权限不足，请联系管理员!\"}");
                out.flush();
                out.close();
            }
        });

        // 持久处理
        http.rememberMe()
                .userDetailsService(userDetailsService) //登录逻辑交给哪个对象
                .tokenValiditySeconds(5000) // 表示持久化时间
                .tokenRepository(repository);   //持久层对象

        return http.build();
    }

}
